package com.fanghuyun.iswaf.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.fanghuyun.iswaf.common.Constants;
import com.fanghuyun.iswaf.common.HttpServletRequestContentWrapper;
import com.fanghuyun.iswaf.common.SysConfig;
import com.fanghuyun.iswaf.service.Action;
import com.fanghuyun.iswaf.util.StringUtil;

public class IsWafFilter implements Filter {
	
	private Logger logger = Logger.getLogger("iswaf");
	
	public void destroy() {
		logger.info("IsWaf destroy.......");
	}

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest req, ServletResponse rep,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)rep;
		try {
			if(request.getRequestURI().endsWith("iswaf.api")&&StringUtil.isNotEmpty("connect_key")&&StringUtil.isNotEmpty("data")){
				Action action = new Action();
				action.runApi(request,response);
				return ;
			}else{
				SysConfig sc = new SysConfig();
				DoFilter doFileter = new DoFilter();
				Map<String, Object> result = doFileter.functionInit(request, response);
				boolean denier = Constants.SYS_CONFIG_DENIER.equals(sc.getSysConfigProperties().getProperty("denier").trim());//denier
				if(denier&&(Boolean)result.get("doChain")){
					chain.doFilter(new HttpServletRequestContentWrapper(request,(Map<String, Object>)result.get(Constants.APP_FILTER_HTTPREQUEST_WRAPPER)), response);
				}else{
					response.getWriter().println("Access Denied");
				}
				return ;
			}
		} catch (Exception e) {
			logger.error("doFilter error.",e);
		}
		chain.doFilter(request, response);//config error dochain
	}

	public void init(FilterConfig config) throws ServletException {
//		List<String> ls = new ArrayList<String>();
//		String fapps[] = config.getInitParameter("not-allowed-filter-apps").split(",");
//		for(String str :fapps){
//			if(!ls.contains(str.trim())){
//				ls.add(str.trim());
//			}
//		}
		logger.info("IsWaf Init. "+config.getFilterName());

	}


}
